<?php /* Smarty version Smarty-3.0.6, created on 2025-08-18 18:10:35
         compiled from "D:\wwwroot\gushi-v2/tpl\v2/painting.html" */ ?>
<?php /*%%SmartyHeaderCode:1482568a2fc1b974dd2-58217447%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_smarty_tpl->decodeProperties(array (
  'file_dependency' => 
  array (
    '7ba8961be1714125417de2a29497b3de50c79704' => 
    array (
      0 => 'D:\\wwwroot\\gushi-v2/tpl\\v2/painting.html',
      1 => 1755511830,
      2 => 'file',
    ),
  ),
  'nocache_hash' => '1482568a2fc1b974dd2-58217447',
  'function' => 
  array (
  ),
  'has_nocache_code' => false,
)); /*/%%SmartyHeaderCode%%*/?>
<?php $_template = new Smarty_Internal_Template("v2/header.html", $_smarty_tpl->smarty, $_smarty_tpl, $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, null, null);
 echo $_template->getRenderedTemplate();?><?php $_template->updateParentVariables(0);?><?php unset($_template);?>
<main class="pt-24 pb-16 bg-paper min-h-screen">
    <section class="container mx-auto px-4">
        <div class="scroll-reveal">
            <h1 class="text-[clamp(1.8rem,4vw,2.8rem)] font-song font-bold mb-2">AI诗画创作</h1>
            <p class="text-lightink max-w-2xl mb-8">以诗入画，以画释诗，AI助您捕捉古典意境</p>
        </div>
        
        <div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
            <!-- 左侧：诗词选择与AI设置 -->
            <div class="lg:col-span-1">
                <div class="bg-ink/5 rounded-2xl p-6 h-full">
                    <h3 class="text-lg font-song font-bold mb-4">诗词选择</h3>
                    
                    <!-- 诗词选择器 -->
                    <div class="mb-6">
                        <select id="poemSelect" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cinnabar mb-4">
                            <option value="">-- 请选择一首诗词 --</option>
                        </select>
                        
                        <button id="aiRecommendPoem" class="w-full flex items-center justify-center gap-2 text-sm border border-cinnabar text-cinnabar px-3 py-2 rounded-lg hover:bg-cinnabar/5 transition-colors mb-4">
                            <i class="fa fa-magic"></i> AI推荐相关诗词
                        </button>
                        
                        <div class="text-sm text-lightink mb-2">或输入自定义诗句</div>
                        <textarea id="customPoem" rows="3" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cinnabar" placeholder="输入您想描绘的诗句..."></textarea>
                    </div>
                    
                    <div id="poemDisplay" class="hidden mb-6">
                        <h4 id="poemTitle" class="font-song font-bold text-lg mb-2"></h4>
                        <p id="poemAuthor" class="text-lightink text-sm mb-4"></p>
                        <div id="poemContent" class="font-kai text-lg leading-relaxed mb-4"></div>
                        <div class="text-sm bg-cinnabar/10 p-2 rounded">
                            <div class="flex items-center mb-1">
                                <i class="fa fa-lightbulb-o mr-1 text-cinnabar"></i>
                                <span class="text-cinnabar font-medium">AI绘画提示词（可编辑）：</span>
                            </div>
                            <textarea id="poemInsight" rows="3" class="w-full p-2 text-sm border border-gray-300 rounded bg-white" placeholder="AI将生成绘画提示词，您可以在此基础上进行修改...">等待诗词选择...</textarea>
                        </div>
                    </div>
                    
                    <!-- AI生成设置 -->
                    <div class="border-t border-gray-200 pt-6 mt-6">
                        <h3 class="text-lg font-song font-bold mb-4">AI创作设置</h3>
                        
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-ink/80 mb-2">艺术风格</label>
                            <select id="artStyle" class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cinnabar">
                                <option value="chinese_ink">中国水墨画</option>
                                <option value="gongbi">工笔画</option>
                                <option value="landscape">山水写意</option>
                                <option value="modern">现代简约</option>
                                <option value="anime">动漫风格</option>
                                <option value="oil">油画风格</option>
                            </select>
                        </div>
                        
                        <div class="mb-4">
                            <label class="block text-sm font-medium text-ink/80 mb-2">细节程度</label>
                            <input type="range" id="detailLevel" min="1" max="5" value="3" class="w-full">
                            <div class="flex justify-between text-xs text-lightink">
                                <span>简约</span>
                                <span>精细</span>
                            </div>
                        </div>
                        
                        <button id="generateWithAI" class="w-full bg-cinnabar text-rice px-4 py-3 rounded-lg hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2 mb-4">
                            <i class="fa fa-magic"></i> AI生成初始图像
                        </button>
                        
                        <button id="aiEnhance" class="w-full border border-cinnabar text-cinnabar px-4 py-2 rounded-lg hover:bg-cinnabar/5 transition-colors flex items-center justify-center gap-2 mb-4 hidden">
                            <i class="fa fa-refresh"></i> AI优化当前画作
                        </button>
                    </div>
                    
                    <!-- 作品保存 -->
                    <div class="border-t border-gray-200 pt-6 mt-6">
                        <h3 class="text-lg font-song font-bold mb-4">作品管理</h3>
                        <input type="text" id="workTitle" placeholder="为您的作品命名..." class="w-full p-3 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-cinnabar mb-4">
                        <button id="savePainting" class="w-full bg-cinnabar text-rice px-4 py-3 rounded-lg hover:bg-opacity-90 transition-colors flex items-center justify-center gap-2">
                            <i class="fa fa-save"></i> 保存作品
                        </button>
                    </div>
                </div>
            </div>
            
            <!-- 右侧：绘画区域与工具 -->
            <div class="lg:col-span-3">
                <div class="bg-ink/5 rounded-2xl p-6">
                    <!-- 创作模式选择 -->
                    <div class="mb-6 bg-white p-4 rounded-lg">
                        <div class="flex flex-wrap gap-4">
                            <button class="creation-mode-btn px-4 py-2 rounded-lg bg-cinnabar text-rice" data-mode="ai">
                                AI辅助创作
                            </button>
                            <button class="creation-mode-btn px-4 py-2 rounded-lg border border-gray-300" data-mode="free">
                                自由创作
                            </button>
                        </div>
                    </div>
                    
                    <!-- 工具条 -->
                    <div class="flex flex-wrap gap-3 mb-6 p-3 bg-white rounded-lg">
                        <div class="flex flex-wrap gap-2">
                            <button class="tool-btn p-2 border border-gray-300 rounded" data-tool="pen" title="画笔">
                                <i class="fa fa-pencil"></i>
                            </button>
                            <button class="tool-btn p-2 border border-gray-300 rounded" data-tool="eraser" title="橡皮擦">
                                <i class="fa fa-eraser"></i>
                            </button>
                            <button class="tool-btn p-2 border border-gray-300 rounded" data-tool="line" title="直线">
                                <i class="fa fa-minus"></i>
                            </button>
                            <button class="tool-btn p-2 border border-gray-300 rounded" data-tool="rect" title="矩形">
                                <i class="fa fa-square-o"></i>
                            </button>
                            <button class="tool-btn p-2 border border-gray-300 rounded" data-tool="text" title="文字">
                                <i class="fa fa-font"></i>
                            </button>
                        </div>
                        
                        <div class="h-8 border-r border-gray-300 mx-2"></div>
                        
                        <div class="flex flex-wrap items-center gap-4">
                            <div class="flex items-center">
                                <label class="mr-2 text-sm">颜色：</label>
                                <input type="color" id="colorPicker" value="#000000" class="w-8 h-8 p-0 border-0 rounded">
                            </div>
                            <div class="flex items-center">
                                <label class="mr-2 text-sm">粗细：</label>
                                <input type="range" id="lineWidth" min="1" max="20" value="3" class="w-24">
                            </div>
                        </div>
                        
                        <div class="h-8 border-r border-gray-300 mx-2"></div>
                        
                        <div class="flex flex-wrap gap-2 ml-auto">
                            <button id="uploadImage" class="tool-btn p-2 border border-gray-300 rounded" title="上传背景图">
                                <i class="fa fa-upload"></i>
                            </button>
                            <input type="file" id="imageUploadInput" accept="image/*" class="hidden">
                            <button id="clearCanvas" class="tool-btn p-2 border border-gray-300 rounded" title="清空画布">
                                <i class="fa fa-trash"></i>
                            </button>
                            <button id="undoAction" class="tool-btn p-2 border border-gray-300 rounded" title="撤销">
                                <i class="fa fa-undo"></i>
                            </button>
                            <button id="redoAction" class="tool-btn p-2 border border-gray-300 rounded" title="重做">
                                <i class="fa fa-repeat"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- 画布区域 -->
                    <div class="relative border-2 border-gray-300 rounded-lg overflow-hidden bg-white">
                        <canvas id="paintingCanvas" class="w-full" height="600"></canvas>
                        
                        <!-- AI生成加载提示 -->
                        <div id="aiGenerating" class="absolute inset-0 bg-ink/70 flex items-center justify-center hidden">
                            <div class="text-center text-rice p-6">
                                <div class="w-16 h-16 border-4 border-rice border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
                                <p class="text-lg">AI正在创作中...</p>
                                <p class="text-sm mt-2 opacity-80">这可能需要10-30秒时间</p>
                            </div>
                        </div>
                        
                        <!-- 初始提示 -->
                        <div id="canvasHint" class="absolute inset-0 flex flex-col items-center justify-center text-lightink">
                            <i class="fa fa-paint-brush text-5xl mb-4 opacity-30"></i>
                            <p>选择诗词后开始创作，或让AI为您生成初始图像</p>
                        </div>
                    </div>
                    
                    <!-- 底部操作区 -->
                    <div class="mt-6 flex flex-wrap justify-between items-center gap-4">
                        <div>
                            <!-- <button id="previewWork" class="border border-gray-300 text-ink px-4 py-2 rounded-lg hover:bg-gray-100 transition-colors">
                                <i class="fa fa-eye mr-1"></i> 预览作品
                            </button> -->
                        </div>
                        
                        <div class="flex gap-4">
                            <!-- <button id="saveAsTemplate" class="border border-gray-300 text-ink px-4 py-2 rounded-lg hover:bg-gray-100 transition-colors">
                                <i class="fa fa-bookmark-o mr-1"></i> 保存为模板
                            </button> -->
                            <button id="shareWork" class="border border-cinnabar text-cinnabar px-4 py-2 rounded-lg hover:bg-cinnabar/5 transition-colors">
                                <i class="fa fa-share-alt mr-1"></i> 分享作品
                            </button>
                        </div>
                    </div>
                </div>
                
                <!-- 作品画廊 -->
                <div class="mt-8 bg-ink/5 rounded-2xl p-6">
                    <h3 class="text-lg font-song font-bold mb-6 flex items-center">
                        <i class="fa fa-th-large mr-2 text-cinnabar"></i>
                        推荐作品
                    </h3>
                    <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-6 gap-4">
                        <div class="aspect-square rounded-lg overflow-hidden border border-gray-200 hover:border-cinnabar transition-colors cursor-pointer">
                            <img src="https://picsum.photos/id/1015/300/300" alt="作品示例" class="w-full h-full object-cover">
                        </div>
                        <div class="aspect-square rounded-lg overflow-hidden border border-gray-200 hover:border-cinnabar transition-colors cursor-pointer">
                            <img src="https://picsum.photos/id/1016/300/300" alt="作品示例" class="w-full h-full object-cover">
                        </div>
                        <div class="aspect-square rounded-lg overflow-hidden border border-gray-200 hover:border-cinnabar transition-colors cursor-pointer">
                            <img src="https://picsum.photos/id/1018/300/300" alt="作品示例" class="w-full h-full object-cover">
                        </div>
                        <div class="aspect-square rounded-lg overflow-hidden border border-gray-200 hover:border-cinnabar transition-colors cursor-pointer">
                            <img src="https://picsum.photos/id/1024/300/300" alt="作品示例" class="w-full h-full object-cover">
                        </div>
                        <div class="aspect-square rounded-lg overflow-hidden border border-gray-200 hover:border-cinnabar transition-colors cursor-pointer">
                            <img src="https://picsum.photos/id/1039/300/300" alt="作品示例" class="w-full h-full object-cover">
                        </div>
                        <div class="aspect-square rounded-lg overflow-hidden border border-gray-200 hover:border-cinnabar transition-colors cursor-pointer flex items-center justify-center text-lightink">
                            <i class="fa fa-plus text-xl"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</main>
<?php $_template = new Smarty_Internal_Template("v2/footer.html", $_smarty_tpl->smarty, $_smarty_tpl, $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, null, null);
 echo $_template->getRenderedTemplate();?><?php $_template->updateParentVariables(0);?><?php unset($_template);?>

<script>
// 初始化画布
const canvas = document.getElementById('paintingCanvas');
const ctx = canvas.getContext('2d');
let isDrawing = false;
let currentTool = 'pen';
let history = [];
let historyIndex = -1;

// 设置画布尺寸
function resizeCanvas() {
    const container = canvas.parentElement;
    const newWidth = container.clientWidth;
    
    // 保存当前画布内容
    const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    
    // 调整尺寸
    canvas.width = newWidth;
    
    // 恢复内容
    if (imageData) {
        ctx.putImageData(imageData, 0, 0);
    }
    
    // 如果画布有内容，隐藏提示
    checkCanvasContent();
}

// 上传背景图
document.getElementById('uploadImage').addEventListener('click', function() {
    document.getElementById('imageUploadInput').click();
});

document.getElementById('imageUploadInput').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(event) {
            const img = new Image();
            img.onload = function() {
                // 清空画布并绘制背景图
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                // 保持比例绘制图片
                const ratio = Math.min(canvas.width / img.width, canvas.height / img.height);
                const newWidth = img.width * ratio;
                const newHeight = img.height * ratio;
                const x = (canvas.width - newWidth) / 2;
                const y = (canvas.height - newHeight) / 2;
                ctx.drawImage(img, x, y, newWidth, newHeight);
            };
            img.src = event.target.result;
        };
        reader.readAsDataURL(file);
    }
});


// 检查画布内容并显示/隐藏提示
function checkCanvasContent() {
    const hasContent = history.length > 0 || 
                      !ctx.getImageData(0, 0, 1, 1).data.every(channel => channel === 0);
    
    if (hasContent) {
        document.getElementById('canvasHint').classList.add('hidden');
        document.getElementById('aiEnhance').classList.remove('hidden');
    } else {
        document.getElementById('canvasHint').classList.remove('hidden');
        document.getElementById('aiEnhance').classList.add('hidden');
    }
}

// 保存当前状态到历史记录
function saveState() {
    // 移除当前状态之后的历史
    if (historyIndex < history.length - 1) {
        history = history.slice(0, historyIndex + 1);
    }
    
    // 保存当前状态
    const state = ctx.getImageData(0, 0, canvas.width, canvas.height);
    history.push(state);
    historyIndex = history.length - 1;
    
    // 限制历史记录数量
    if (history.length > 20) {
        history.shift();
        historyIndex--;
    }
    
    checkCanvasContent();
}

// 初始化
resizeCanvas();
window.addEventListener('resize', resizeCanvas);

// 绘画逻辑
canvas.addEventListener('mousedown', startDrawing);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDrawing);
canvas.addEventListener('mouseout', stopDrawing);

function startDrawing(e) {
    isDrawing = true;
    ctx.beginPath();
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    ctx.moveTo(x, y);
}

function draw(e) {
    if (!isDrawing) return;
    
    const rect = canvas.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;
    
    ctx.lineWidth = document.getElementById('lineWidth').value;
    ctx.lineCap = 'round';
    
    if (currentTool === 'pen') {
        ctx.strokeStyle = document.getElementById('colorPicker').value;
        ctx.lineTo(x, y);
        ctx.stroke();
    } else if (currentTool === 'eraser') {
        ctx.strokeStyle = 'white';
        ctx.lineTo(x, y);
        ctx.stroke();
    }
    // 可以添加其他工具的实现...
}

function stopDrawing() {
    if (isDrawing) {
        isDrawing = false;
        saveState(); // 保存当前状态
    }
}

// 工具切换
document.querySelectorAll('.tool-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        document.querySelectorAll('.tool-btn').forEach(b => b.classList.remove('bg-gray-200'));
        this.classList.add('bg-gray-200');
        currentTool = this.dataset.tool;
    });
});

// 创作模式切换
document.querySelectorAll('.creation-mode-btn').forEach(btn => {
    btn.addEventListener('click', function() {
        document.querySelectorAll('.creation-mode-btn').forEach(b => {
            b.classList.remove('bg-cinnabar', 'text-rice');
            b.classList.add('border', 'border-gray-300');
        });
        this.classList.remove('border', 'border-gray-300');
        this.classList.add('bg-cinnabar', 'text-rice');
        
        // 根据模式显示/隐藏AI功能
        const isAIMode = this.dataset.mode === 'ai';
        if (isAIMode) {
            document.querySelectorAll('#generateWithAI, #aiEnhance').forEach(el => {
                el.classList.remove('hidden');
            });
        } else {
            document.getElementById('generateWithAI').classList.add('hidden');
            // 保留增强功能
        }
    });
});

// 清空画布
document.getElementById('clearCanvas').addEventListener('click', function() {
    if (confirm('确定要清空画布吗？')) {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        history = [];
        historyIndex = -1;
        checkCanvasContent();
    }
});

// 撤销/重做
document.getElementById('undoAction').addEventListener('click', function() {
    if (historyIndex > 0) {
        historyIndex--;
        ctx.putImageData(history[historyIndex], 0, 0);
    }
});

document.getElementById('redoAction').addEventListener('click', function() {
    if (historyIndex < history.length - 1) {
        historyIndex++;
        ctx.putImageData(history[historyIndex], 0, 0);
    }
});

// 诗词选择逻辑
document.getElementById('poemSelect').addEventListener('change', function() {
    const poemId = this.value;
    if (poemId) {
        fetch('/index.php?c=main&a=getPoemDetail&id=' + poemId)
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    document.getElementById('poemTitle').textContent = data.data.title;
                    document.getElementById('poemAuthor').textContent = data.data.author + ' · ' + data.data.dynasty;
                    // 将\n替换为<br>并使用innerHTML
                    document.getElementById('poemContent').innerHTML = data.data.content.replace(/\\n/g, '<br />');
                    document.getElementById('poemDisplay').classList.remove('hidden');
                    
                    // 获取AI解读（改为流式输出）
                    getPoemInsight(data.data.content);
                }
            });
    }
});

// 自定义诗句输入
document.getElementById('customPoem').addEventListener('input', function() {
    if (this.value.trim()) {
        document.getElementById('poemTitle').textContent = '自定义诗句';
        document.getElementById('poemAuthor').textContent = '原创';
        // 将换行符替换为<br>
        document.getElementById('poemContent').innerHTML = this.value.replace(/\n/g, '<br />');
        document.getElementById('poemDisplay').classList.remove('hidden');
        
        // 获取AI解读
        getPoemInsight(this.value);
    } else {
        document.getElementById('poemDisplay').classList.add('hidden');
    }
});

// AI解读诗句
// AI解读诗句（改为流式输出）
function getPoemInsight(content) {
    const insightElement = document.getElementById('poemInsight');
    insightElement.value = 'AI正在生成绘画提示词...';
    
    // 使用Fetch API发送非流式请求
    fetch('/index.php?c=main&a=analyzePoemStream', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'content=' + encodeURIComponent(content)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('生成提示词失败');
        }
        
        // 直接解析JSON响应
        return response.json();
    })
    .then(data => {
        // 检查是否成功获取数据
        if (data.code === 1 && data.data && data.data.prompt) {
            // 显示生成的绘画提示词（去掉前缀，因为HTML中已有）
            insightElement.value = data.data.prompt;
        } else {
            console.error('生成提示词失败:', data.message || '未知错误');
            insightElement.value = '生成失败 - ' + (data.message || '未知错误');
        }
    })
    .catch(error => {
        insightElement.value = '生成过程出错 - ' + error.message;
    });
}

// AI推荐诗词
document.getElementById('aiRecommendPoem').addEventListener('click', function() {
    this.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 推荐中...';
    this.disabled = true;
    
    fetch('/index.php?c=ai&a=recommendPoems')
        .then(response => response.json())
        .then(data => {
            this.innerHTML = '<i class="fa fa-magic"></i> AI推荐相关诗词';
            this.disabled = false;
            
            if (data.code === 1 && data.list.length > 0) {
                // 清空并添加推荐的诗词
                const select = document.getElementById('poemSelect');
                select.innerHTML = '<option value="">-- 请选择一首诗词 --</option>';
                
                data.list.forEach(poem => {
                    const option = document.createElement('option');
                    option.value = poem.id;
                    option.textContent = poem.title + ' - ' + poem.author;
                    select.appendChild(option);
                });
                
                // 提示用户
                showToast('AI已为您推荐相关诗词，请选择');
            }
        });
});

// AI生成图像
document.getElementById('generateWithAI').addEventListener('click', function() {
    const poemContent = document.getElementById('poemContent')?.textContent || 
                       document.getElementById('customPoem').value;
    
    if (!poemContent) {
        showToast('请先选择或输入诗词', true);
        return;
    }
    
    // 获取用户可编辑的提示词
    const prompt = document.getElementById('poemInsight').value;
    
    if (!prompt || prompt === '等待诗词选择...' || prompt === 'AI绘画提示词：未能理解诗句意境' || prompt === '生成失败 - 未知错误') {
        showToast('请先等待AI生成提示词或手动输入提示词', true);
        return;
    }


    // 显示加载状态
    document.getElementById('aiGenerating').classList.remove('hidden');
    this.disabled = true;
    this.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 生成中...';
    
    const style = document.getElementById('artStyle').value;
    const detail = document.getElementById('detailLevel').value;
    const poemId = document.getElementById('poemSelect').value || '';
    
    fetch('/index.php?c=main&a=generatePainting', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'poem=' + encodeURIComponent(poemContent) + 
              '&style=' + style + 
              '&detail=' + detail +
              '&prompt=' + encodeURIComponent(prompt) +
              '&poem_id=' + encodeURIComponent(poemId)
    })
    .then(response => response.json())
    .then(data => {
        // 隐藏加载状态
        document.getElementById('aiGenerating').classList.add('hidden');
        this.disabled = false;
        this.innerHTML = '<i class="fa fa-magic"></i> AI生成初始图像';
        
        if (data.code === 1 && data.data.url) {
            // 加载生成的图像到画布
            const img = new Image();
            img.crossOrigin = 'anonymous';
            img.onload = function() {
                // 清空画布并绘制图像
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                
                // 计算缩放比例以适应画布
                const scale = Math.min(canvas.width / img.width, canvas.height / img.height);
                const x = (canvas.width - img.width * scale) / 2;
                const y = (canvas.height - img.height * scale) / 2;
                
                ctx.drawImage(img, x, y, img.width * scale, img.height * scale);
                saveState(); // 保存状态
                showToast('AI图像生成成功');
            };
            img.src = data.data.url;
        } else {
            showToast('图像生成失败：' + (data.msg || '未知错误'), true);
        }
    });
});

// AI优化当前画作
document.getElementById('aiEnhance').addEventListener('click', function() {
    // 获取用户可编辑的提示词
    const prompt = document.getElementById('poemInsight').value;
    
    if (!prompt || prompt === '等待诗词选择...' || prompt === 'AI正在生成绘画提示词...' || prompt === '生成失败 - ' || prompt.startsWith('生成过程出错 - ')) {
        showToast('请先等待AI生成提示词或手动输入提示词', true);
        return;
    }
    const poemContent = document.getElementById('poemContent')?.textContent || 
                       document.getElementById('customPoem').value;
    
    if (!poemContent) {
        showToast('请先选择或输入诗词', true);
        return;
    }
    const style = document.getElementById('artStyle').value;
    const detail = document.getElementById('detailLevel').value;
    const poemId = document.getElementById('poemSelect').value || '';
    
    // 显示加载状态
    document.getElementById('aiGenerating').classList.remove('hidden');
    this.disabled = true;
    this.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 优化中...';
    
    // 获取当前画布内容
    const imageData = canvas.toDataURL('image/png');
    
    fetch('/index.php?c=main&a=generatePainting', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'poem=' + encodeURIComponent(poemContent) + 
              '&style=' + style + 
              '&detail=' + detail +
              '&prompt=' + encodeURIComponent(prompt) +
              '&poem_id=' + encodeURIComponent(poemId)
    })
    .then(response => response.json())
    .then(data => {
        // 隐藏加载状态
        document.getElementById('aiGenerating').classList.add('hidden');
        this.disabled = false;
        this.innerHTML = '<i class="fa fa-refresh"></i> AI优化当前画作';
        
        if (data.code === 1 && data.data.url) {
            // 加载优化后的图像
            const img = new Image();
            img.crossOrigin = 'anonymous';
            img.onload = function() {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                saveState(); // 保存状态
                showToast('AI优化成功');
            };
            img.src = data.data.url;
        } else {
            showToast('优化失败：' + (data.msg || '未知错误'), true);
        }
    });
});

// 保存作品
document.getElementById('savePainting').addEventListener('click', function() {
    const poemId = document.getElementById('poemSelect').value;
    const customPoem = document.getElementById('customPoem').value;
    const workTitle = document.getElementById('workTitle').value || '我的诗画作品';
    
    if (!poemId && !customPoem) {
        showToast('请先选择或输入诗词', true);
        return;
    }
    
    // 检查画布是否有内容
    if (history.length === 0 && 
        ctx.getImageData(0, 0, 1, 1).data.every(channel => channel === 0)) {
        showToast('请先创作您的作品', true);
        return;
    }
    
    const imageData = canvas.toDataURL('image/png');
    const poemTitle = document.getElementById('poemTitle').textContent;
    
    this.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 保存中...';
    this.disabled = true;
    
    fetch('/index.php?c=main&a=savePainting', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: 'poem_id=' + (poemId || '') + 
              '&custom_poem=' + encodeURIComponent(customPoem || '') +
              '&image_data=' + encodeURIComponent(imageData) + 
              '&title=' + encodeURIComponent(workTitle) +
              '&original_title=' + encodeURIComponent(poemTitle)
    })
    .then(response => response.json())
    .then(data => {
        this.innerHTML = '<i class="fa fa-save"></i> 保存作品';
        this.disabled = false;
        
        if (data.code === 1) {
            showToast('作品保存成功！');
            setTimeout(() => {
                window.location.href = '/index.php?c=main&a=userWorks';
            }, 1500);
        } else {
            showToast('保存失败：' + (data.msg || '未知错误'), true);
        }
    });
});

// 页面加载时获取诗词列表
window.onload = function() {
    fetch('/index.php?c=main&a=getPoemList')
        .then(response => response.json())
        .then(data => {
            if (data.code === 1) {
                const select = document.getElementById('poemSelect');
                data.data.list.forEach(poem => {
                    const option = document.createElement('option');
                    option.value = poem.id;
                    option.textContent = poem.title + ' - ' + poem.author;
                    select.appendChild(option);
                });
            }
        });
};
</script>